﻿using Services4KouDai.Encrypt;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace ServiceTest
{
    public class PhoneEncryptor : IEncrypt
    {
        public string AESEncrypt(string dataToEncrypt, string key, string salt)
        {
            AesManaged aes = null;
            MemoryStream memoryStream = null;
            CryptoStream cryptoStream = null;

            try
            {
                //Generate a Key based on a Password, Salt and HMACSHA1 pseudo-random number generator 
                //Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt));

                //Create AES algorithm with 256 bit key and 128-bit block size 
                aes = new AesManaged();
                aes.Key = string2Byte(key);
                aes.IV = Encoding.UTF8.GetBytes("0102030405060708");

                //Create Memory and Crypto Streams 
                memoryStream = new MemoryStream();
                cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

                //Encrypt Data 
                byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
                cryptoStream.Write(data, 0, data.Length);
                cryptoStream.FlushFinalBlock();

                //Return Base 64 String 
                return Convert.ToBase64String(memoryStream.ToArray());
            }
            finally
            {
                if (cryptoStream != null)
                    cryptoStream.Close();

                if (memoryStream != null)
                    memoryStream.Close();

                if (aes != null)
                    aes.Clear();
            }
        }

        public byte[] string2Byte(String str)
        {
            byte[] result = new byte[str.Length / 2];
            for (int i = 0; i < result.Length; i++)
            {
                byte b = (byte)((((getStrIndex(str[2 * i])) & 0x0f) << 4) | ((getStrIndex(str[2 * i + 1])) & 0x0f));
                result[i] = b;
            }
            return result;
        }

        public int getStrIndex(char c)
        {
            if (c > '9')
            {
                return 10 + (c - 'a');
            }
            else
            {
                return c - '0';
            }
        }
    }
}
